package com.jetinno.simple

import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.StringRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jetinno.simple.SimpleApplication.Companion.sContext
import com.jetinno.simple.utils.ResourcesUtil
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Created by zhangyuncai on 2021/7/29.
 */
open class SimpleVM : ViewModel() {

    val TAG = this::class.java.simpleName

    val mainHandler = Handler(Looper.getMainLooper())

    fun getContext(): Context {
        return sContext
    }

    open fun runOnUiThread(runnable: Runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run()
        } else {
            mainHandler.post(runnable)
        }
    }

    /**
     * 延时一段时间收到消息
     * @param time 延时时间,毫秒
     * @param callback 延时时间已到回调
     */
    protected fun delayTime(time: Long, callback: ((Boolean) -> Unit)): Job {
        return viewModelScope.launch {
            try {
                delay(time)
                callback.invoke(true)
            } catch (throwable: Throwable) {
                throwable.printStackTrace()
            }
        }
    }

    fun getString(@StringRes id: Int): String {
        return ResourcesUtil.getString(id)
    }

    open fun onDestory() {

    }

    override fun onCleared() {
        super.onCleared()
    }

}
